package com.example.com.example.imooc.AsynTask;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.LruCache;
import android.widget.ImageView;
import android.widget.ListView;

import com.examplee.username.httpfrist_01.R;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by usernamee on 2017/7/28.
 */

public class imageLoader {
    String murl;
    ImageView imagview;
//    创建Cache用来缓存
    private LruCache<String,Bitmap> mCaches;

//存著listview
    ListView mListView;
//创建一个聚合来去管理tag
    Set<NewsAsynTask> mTask;
    public  imageLoader(ListView listView){
        mListView=listView;
        mTask=new HashSet<>();
//        获取最大可用内存
        int maxMemory= (int) Runtime.getRuntime().maxMemory();
        int cacheSize=maxMemory/4;
        mCaches=new LruCache<String,Bitmap>(cacheSize){
            @Override
            protected int sizeOf(String key, Bitmap value) {
//                在每次存入缓存的时候调用
                return value.getByteCount();//获取实际的大小
            }
        };


    }
//    增加到缓存
    public void addBitmapToCache(String url,Bitmap bitmap){
        if (getBitmapFromCache(url)==null){
            mCaches.put(url,bitmap);
        }
    }
//    从缓存中获取数据
    public Bitmap getBitmapFromCache(String url){
        return mCaches.get(url);//mCaches和map差不多
    }
    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (imagview.getTag().equals(murl)) {
                imagview.setImageBitmap((Bitmap) msg.obj);

            }
        }


    };

    public void showImageByThread(ImageView imageView, final String url) {
        imagview = imageView;
        murl = url;
        new Thread() {

            @Override
            public void run() {
                super.run();
                Bitmap bitmap1 = getBitmapFromURL(url);
                Message message = Message.obtain();
                message.obj = bitmap1;
                mHandler.sendMessage(message);
            }
        }.start();
    }

    public Bitmap getBitmapFromURL(String urlString) {
        Bitmap bitmap;
        InputStream is = null;
        try {
            URL url = new URL(urlString);

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            is = new BufferedInputStream(connection.getInputStream());
            bitmap = BitmapFactory.decodeStream(is);
            connection.disconnect();//释放资源
//            Thread.sleep(1000);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            try {
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public void showImagesAsynTask(ImageView imageView,String url){
//        从缓存中取出对应的图片
        Bitmap bitmap=getBitmapFromCache(url);
        if (bitmap==null){
//            如果没有图片，就下载
//            new NewsAsynTask(url).execute(url);
             imageView.setImageResource(R.drawable.imgasyn);
        }else{
            imageView.setImageBitmap(bitmap);
        }

    }
    public void cancelAllTask(){
        if (mTask!=null){
            for(NewsAsynTask task:mTask){
                task.cancel(false);//取消掉
            }
        }
    }
//    用来加载从start到end的所有图片
    public void loadImages(int start,int end){
        for (int i=start;i<end;i++){
            String url=NewsAdapter.URLS[i];
            Bitmap bitmap=getBitmapFromCache(url);
            if (bitmap==null){
//            如果没有图片，就下载
//                new NewsAsynTask(mListView,url).execute(url);
                NewsAsynTask task=new NewsAsynTask(url);
                task.execute(url);
                mTask.add(task);
            }else{
                ImageView imageView= (ImageView) mListView.findViewWithTag(url);//通过url来找到ImageView
                imageView.setImageBitmap(bitmap);
            }
        }
    }
    private class NewsAsynTask extends AsyncTask<String,Void,Bitmap> {
//       ImageView mImageview;
     String mUrl;
        public NewsAsynTask(String url){
//            mImageview=imagview;
            mUrl=url;
        }
        @Override
        protected Bitmap doInBackground(String... params) {
//            return getBitmapFromURL(params[0]);
            String url=params[0];
//            从网络上获取图片
            Bitmap bitmap=getBitmapFromURL(url);
            if (bitmap!=null){
//                将不再缓存图片
                addBitmapToCache(url,bitmap);
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
//            if (mImageview.getTag().equals(mUrl))
//            mImageview.setImageBitmap(bitmap);
            ImageView imageView= (ImageView) mListView.findViewWithTag(mUrl);
            if (imageView!=null &&bitmap!=null){
                imageView.setImageBitmap(bitmap);
            }
            mTask.remove(this);
        }

    }
}
